<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>管理员名单</span>
        <el-input
          placeholder="搜索管理员用户或姓名"
          v-model="searchQuery"
          clearable
          style="width: 200px;margin-right: 20px;"
        />
        <div class="extra">
          <el-button @click="clearForm" type="primary">添加管理员</el-button>
          <el-button 
            :disabled="selectedAdmins.length === 0" 
            @click="deleteSelectedAdmins" 
            type="danger">
            批量删除
          </el-button>
        </div>
      </div>
    </template>

    <!-- 添加管理员弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form :model="adminModel" :rules="rules" label-width="100px" style="padding-right: 30px">
        <el-form-item label="管理员账户" prop="username">
          <el-input v-model="adminModel.username" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="adminModel.name" minlength="2" maxlength="6"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adminModel.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="adminModel.phone"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="title === '添加管理员' ? addAdmin() : editAdmin()">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 列表 -->
    <el-table :data="paginatedAdmins" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="序号" width="80" type="index"> </el-table-column>
      <el-table-column label="管理员用户" prop="username"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="手机" prop="phone"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showAdmin(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteAdmin(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="handlePageChange"
      :total="filteredAdmins.length"
      style="margin-top: 20px;">
    </el-pagination>
  </el-card>
</template>

<script setup>
import { Edit, Delete } from '@element-plus/icons-vue';
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getAllUserDataService,
  addAdminService,
  updateUserInfoService,
  deleteService,
} from '../../api/user';

const admins = ref([]);
// 弹框标题
const title = ref('');
// 控制添加管理员弹窗
const dialogVisible = ref(false);
// 添加管理员数据模型
const adminModel = ref({
  username: '',
  name: '',
  email: '',
  phone: '',
  id: 0,
});

// 添加管理员表单校验
const rules = {
  username: [
    { required: true, message: '请输入管理员名称', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入管理员姓名', trigger: 'blur' },
    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
  ],
};

// 显示管理员列表信息
const adminList = async () => {
  let res = await getAllUserDataService();
  admins.value = res.data;
};

// 搜索关键词
const searchQuery = ref('');

// 计算出匹配搜索条件的管理员列表
const filteredAdmins = computed(() => {
  return admins.value.filter(admin =>
    admin.username.includes(searchQuery.value) ||
    admin.name.includes(searchQuery.value)
  );
});

// 计算分页后的管理员数据
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示的管理员数

const paginatedAdmins = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return filteredAdmins.value.slice(start, start + pageSize.value);
});

// 处理选择变化的方法
const selectedAdmins = ref([]);

const handleSelectionChange = (selection) => {
  selectedAdmins.value = selection;
};

// 批量删除选中的管理员
const deleteSelectedAdmins = async () => {
  if (selectedAdmins.value.length === 0) {
    ElMessage.warning('请选择要删除的管理员');
    return;
  }
  ElMessageBox.confirm('您确定要删除这些管理员吗?', '注意', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async () => {
    for (const admin of selectedAdmins.value) {
      await deleteService(admin.id);
    }
    selectedAdmins.value = []; // 清空选择
    adminList(); // 刷新管理员列表
    ElMessage.success('删除成功');
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '删除已取消',
    });
  });
};

// 页码改变事件
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 添加管理员弹窗
const addAdmin = async () => {
  let res = await addAdminService(adminModel.value);
  if (res) {
    ElMessage.success(res.message ? res.message : '添加成功');
    adminList();
    dialogVisible.value = false;
  } else {
    ElMessage.error(res.message ? res.message : '很可惜，添加失败了');
  }
};

// 清空表单数据
const clearForm = () => {
  adminModel.value = {
    username: '',
    name: '',
    email: '',
    phone: '',
    id: 0,
  };
  title.value = '添加管理员';
  dialogVisible.value = true;
};

// 显示管理员的信息到编辑弹窗
const showAdmin = (row) => {
  title.value = '编辑管理员';
  adminModel.value = { ...row };
  dialogVisible.value = true;
};

// 编辑管理员
const editAdmin = async () => {
  let res = await updateUserInfoService(adminModel.value);
  if (res) {
    ElMessage.success(res.message ? res.message : '修改成功');
    adminList();
    dialogVisible.value = false;
  } else {
    ElMessage.error(res.message ? res.message : '很可惜，修改失败了');
  }
};

// 删除管理员
const deleteAdmin = async (row) => {
  ElMessageBox.confirm('您确定要删除这个管理员吗?', '注意', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async () => {
    let res = await deleteService(row.id);
    if (res) {
      ElMessage.success(res.message ? res.message : '删除成功');
      adminList();
    } else {
      ElMessage.error(res.message ? res.message : '很可惜，删除失败了');
    }
  })
  .catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 初始化管理员列表
adminList();
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>